home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9596 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: ?Help - struct array of strings
  5. Date: 11 Mar 1996 13:56:33 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4i27ihINN333@keats.ugrad.cs.ubc.ca>
  8. References: <4hvpgp$gu7@ftp.netgate.net>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4hvpgp$gu7@ftp.netgate.net>,
  12. Tamara Johnson  <malihini@netgate.net> wrote:
  13. >/*
  14. >   program to enter author(s), title(s)
  15. >   then display entries.
  16. >   why is printf displaying strange things?
  17. >   (see output at end)
  18. >*/
  19. >
  20. >#include <stdlib.h>
  21. >#include <stdio.h>
  22. >#include <conio.h>
  23. >#include <string.h>
  24. >
  25. >#define MAX 5
  26.  
  27. MAX is 5.
  28.  
  29. >struct catalog{
  30. >  char name[80];        /* author name */
  31. >  char title[80];    /* title */ 
  32. >}cat[80];
  33.  
  34. But array has 80 things? Why not cat[MAX]?
  35.  
  36. >void main()
  37.  ^^^^
  38.  
  39. Bad! You are not free to give main() any old return type. The required type is
  40. int.
  41.  
  42. >{
  43. >int i;
  44. >
  45. >for(i=0;i<MAX;i++) 
  46. >  {
  47. >  printf("Enter author name (ENTER to quit); ");
  48. >  gets(cat[i].name);
  49.  
  50. The gets function is "bad". The user could type more than the available buffers
  51. space. But you can get away with it here, I suppose.
  52.  
  53. >  if(!*cat[i].name) break;
  54. >  printf("Enter title: ");
  55. >  gets(cat[i].title);
  56. >  }
  57. >for(i=0;i<MAX;i++)
  58.  
  59. The user could have entered fewer than MAX record. Break out of the loop as you
  60. did above.
  61.  
  62. >  printf("%c %c\n", cat[i].name, cat[i].title);
  63.  
  64. The %c conversion specifier calls for a char type. You are giving it a pointer
  65. to char. The pointers are being interpreted as characters, yielding undefined
  66. behavior. You want the %s specifier.
  67.  
  68. If you really want to print just the first character of each name and title,
  69. you must do it like this:
  70.  
  71.     printf("%c %c\n", *cat[i].name, cat[i].title[0]);
  72.  
  73. Both methods produce the first character; the first is what you used in your
  74. input loop to check for the first character being a zero.
  75.  
  76. There should be a return value here. Main is a function returning int, and
  77. requires a return value, otherwise the exit status of the program is undefined:
  78.  
  79.     return 0;
  80.  
  81. >}
  82. -- 
  83.  
  84.